#pragma once

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <unistd.h>
#include <string>
// #include "log.hpp"

const int backlog = 10;

enum
{
    SocketErr = 1,
    BindErr,
    ListenErr,
};

class sock
{
public:
    sock()
    {
    }

    ~sock()
    {
    }

public:
    int Socket(int type = SOCK_STREAM, int protocol = 0)
    {
        _sockfd = socket(AF_INET, type, protocol);
        if (_sockfd < 0)
        {
            std::cerr << "socket failed \n";
            //exit(SocketErr);
            return -1;
        }
        return _sockfd;
    }

    void Bind(uint16_t port)
    {
        sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);
        if (bind(_sockfd, (const sockaddr *)&local, len) < 0)
        {
            std::cerr << "bind failed" << std::endl;
            exit(BindErr);
        }
    }

    void Listen()
    {
        if (listen(_sockfd, backlog) < 0)
        {
            std::cerr << "listen failed" << std::endl;
            exit(ListenErr);
        }
    }

    int Accept(std::string *clientip, uint16_t *clientport)
    {
        sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(_sockfd, (sockaddr *)&peer, &len);
        if (newfd < 0)
        {
            std::cerr << "accept failed" << std::endl;
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port);
        return newfd;
    }

    bool Connect(const std::string& ip, uint16_t port)
    {
        sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family=AF_INET;
        peer.sin_port=htons(port);
        inet_pton(AF_INET,ip.c_str(),&peer.sin_addr);
        if(connect(_sockfd,(const sockaddr*)&peer,sizeof(peer))<0)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }

    int Getfd()
    {
        return _sockfd;
    }

    void Close()
    {
        close(_sockfd);
    }

private:
    int _sockfd;
};